package com.xiaoxiang.auth.service.impl;

import com.xiaoxiang.auth.constant.AuthConstant;
import com.xiaoxiang.auth.entity.Role;
import com.xiaoxiang.auth.entity.User;
import com.xiaoxiang.auth.result.AuthResult;
import com.xiaoxiang.auth.service.BaseAuthService;
import com.xiaoxiang.auth.service.UserService;
import com.xiaoxiang.auth.util.JwtUtil;
import com.xiaoxiang.common.exception.CommonException;
import com.xiaoxiang.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: haha
 * @date: 2022/3/20 20:03
 */
@Service("phoneAuthService")
public class PhoneAuthServiceImpl extends BaseAuthService {


    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private UserService userService;

    @Value("${auth.phone.code.maxCount}")
    private Integer maxCount;

    @Value("${auth.phone.code.time}")
    private Integer time;

    @Value("${token.expire}")
    private long expire;

    @Override
    public AuthResult auth(String phone, String code) {
        String codeCount = redisTemplate.opsForValue()
                .get(AuthConstant.PHONE_CODE_COUNT_KEY + phone);
        if (codeCount == null || Integer.parseInt(codeCount) > maxCount) {
            throw new CommonException(ResultCodeEnum.DATA_BUSY);
        }
        String resCode = redisTemplate.opsForValue().get(AuthConstant.PHONE_CODE_KEY + phone);
        if (resCode == null) {
            throw new CommonException(ResultCodeEnum.CODE_EXPIRE);
        }
        if (!resCode.equals(code)) {
            throw new CommonException(ResultCodeEnum.CODE_ERROR);
        }
        User user = userService.queryByPhone(phone);
        List<Role> roles = roleService.queryRoleByUserId(user.getId());
        String token = JwtUtil.createToken(user.getId(),
                roles.stream().map(Role::getId).collect(Collectors.toList()),
                roles.stream().map(Role::getRoleName).collect(Collectors.toList()), user.getUsername());
        return AuthResult.builder()
                .username(user.getUsername())
                .imgUrl(user.getImgUrl())
                .expire(System.currentTimeMillis() + 1000 * expire)
                .token(token).build();
    }

    @Override
    public int getCode(String code) {
        return 0;
    }
}
